// import u from './v3.utils.js'
// import {v3Utils as u} from './mfc-init.js'//

// window.$v3.doNothing('v3Utils and u--:',u)//
import {loadCss} from './mfc-style-loader.js'
let u = window.$v3.$utils;

const DOT_MFC_POSTFIX_STR='.m.htm'
// const DOT_MFC_POSTFIX_STR='.mfc'

export const DOT_MFC_POSTFIX=DOT_MFC_POSTFIX_STR

u.insertRule = (function () {

    let lastRuleStr = null;
    // let strCache = []
    let maxIndex = -1;
    function getStyleSheet(unique_title) {
        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i];
            if (sheet.rules.length <= 10) {
                return sheet;
            }
            // if (sheet.title == unique_title) {
            //     return sheet;
            // }
        }
    }

    return function (str, isAddRule = true, updateLastRule = true) {

        // if (strCache.includes(str)) {
        //     return
        // }
        // strCache.push(str)
        maxIndex++;
        let sheet = getStyleSheet()


        if (isAddRule && lastRuleStr != null) {
            window.$v3.doNothing('will remove some class')
            u.removeRule(str, false, false)
        }

        sheet[isAddRule ? 'insertRule' : 'removeRule'](str, maxIndex);
        u.insertRule.sheet = sheet;


        if (isAddRule && updateLastRule) {
            lastRuleStr = str;
        }

    }

})();

u.removeRule = (rule) => u.insertRule(rule, false)

let doConsoleLog = () => { }


export const generateNewPathByRelativePath = function (path, mfcFilePath) {
    return __REQUIRE(path, mfcFilePath)
}

function __REQUIRE(path, mfcFilePath = null) {
    // function __REQUIRE(path,thisPath=null){
    let doConsoleLog = () => { }
    // if(thisPath===null){
    //     return generateNewPathByRelativePath(path,thisPath)
    // }




    function basePath(path) {
        return path.split('/').slice(0, -1).join('/')
    }
    function generateNewPathByRelativePath(path, thisPath) {
        // alert(path)
        path = path.trim()

        if ((path.startsWith('http://')) || (path.startsWith('https://'))) {
            return path;
        }

        if (!(path.startsWith('/')) && !(path.startsWith('./')) && !(path.startsWith('../')) && !(path.startsWith('http://')) && !(path.startsWith('https://'))) {
            throw 'path must starts with ./ or ../ or http:// or https:// or /'
        }

        doConsoleLog("sdfdsf path---:", path)
        let finalPath;
        if ((path.startsWith('./'))) {
            // if(path.startsWith('./')){
            path = path.substring(2)
            // }
            finalPath = basePath(thisPath) + '/' + path;

        } else {
            let base = basePath(thisPath);

            let doubleDotCount = path.split('../').length - 1
            // let reg=new RegExp('\.\./','gm');
            // doConsoleLog('reg and path--:',reg,path,path.replace(reg,''))
            let result = base.split('/').slice(0, 0 - doubleDotCount).join('/') + '/' + path.split('../').join("")
            // let result=base.split('/').slice(0,0-doubleDotCount).join('/')+'/'+path.replace(/\.\.\//gi,'')
            finalPath = result;
            // doConsoleLog('base and path---:',base,path,'--',result)
        }
        if (!finalPath.startsWith("http://") && !finalPath.startsWith("https://")) {
            finalPath = finalPath.replace(new RegExp('//', 'gi'), '/');
            // finalPath = finalPath.substring(1, finalPath.length);
        }
        let str = finalPath;
        let arr = str.split('://');
        if (arr.length > 1) {

            arr = arr.map((s, index) => {
                // console.log(s)
                if (index == 0) { return s; }
                return s.split('//').join('/')

            })
        }
        arr = arr.join('://')
        // console.log('arr---:',arr)
        return arr;


    }
    if (mfcFilePath) {
        return generateNewPathByRelativePath(path, mfcFilePath)
    }



    path = generateNewPathByRelativePath(path, this.thisPath)

    path = path.toLowerCase();
    // console.log('aaaaaaaa', path.split('?')[0]);
    if (path.split('?')[0].endsWith(this.DOT_MFC_POSTFIX_STR)) {
        return path;
        // return generateNewPathByRelativePath(path)
    }
    else if (path.split('?')[0].endsWith('.m.css')){

        var link = document.createElement('link');
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = path;
        
        document.head.appendChild(link);

        // this.__HTTP_GET_STR(path).then((str) =>{
        //     this.__INSERT_GLOBAL_STYLE(str)
        //     // console.log('str---:',str)
        // })
    }
    // else if (path.split('?')[0].endsWith('.mless')) {


        
    //     this.__HTTP_GET_STR(path).then((myLessCode) => {
    //         // console.log('res---:',res)


    //         // var parser = new (less.Parser);

    //         // parser.parse(myLessCode, function (err, tree) {
    //         //     if (err) { return console.error(err) }
    //         //     css = tree.toCSS();
    //         //     console.log('css code--:',css);
    //         // });
    //     })
    // }
    else if (path.split('?')[0].endsWith('.js') || path.split('?')[0].endsWith('.m.js')) {
        let resolver;
        let prom = new Promise((resolve) => {
            resolver = resolve;
        })

        prom.loadAsType = 'js'
        prom.loadAsParam = null
        prom.loadAs = (type, param) => {
            prom.loadAsType = type
            prom.loadAsParam = param;
            return prom;
        }

        setTimeout(() => {
            let importPath=path + (!path.includes('?no_cache')?('?' + window.$v3.appHash):'')
            // alert(importPath)
            window.__IMPORT(importPath)
                .then((res) => {
                    // alert(prom.loadAsType)
                    if (prom.loadAsType == 'js') {
                        resolver(res.default);
                    } else{
                        resolver()
                    }
                    
                    // else if (prom.loadAsType == 'css') {
                    //     // alert('t')
                    //     // function upper(all,letter){
                    //     //     return '"'+letter+'"';
                    //     // }
                    //     let str = res.default(prom.loadAsParam)?.trim() || ''
                    //     if (str.startsWith('<style>') && str.endsWith('</style>')) {
                    //         str = str.split('<style>')[1]
                    //             .split('</style>')[0];

                    //         this.__INSERT_GLOBAL_STYLE(str, resolver)

                    //         // window.$v3.doNothing('str in load css--:',str,obj)//
                    //     } else {
                    //         throw 'css content must starts with <style> and ends with </style>'
                    //     }

                    // }

                    doConsoleLog('res---:', res)
                })
        })


        // _loadJS.then(()=>{

        // })
        return prom;
        // return {
        //     __PROM:prom
        // }

    }
    // else if(path.split('?')[0].endsWith('.style')){
    //     this.__HTTP_GET_STR(path)
    //         .then((res)=>{
    //             window.$v3.doNothing('style res---:',res)
    //             // resolver(JSON.parse(res))
    //             // window.$v3.doNothing('res of http get type---:',window.$v3.$typeof(res))
    //         })
    // }
    else if (path.split('?')[0].endsWith('.json')) {
        // alert(path)


        let resolver;
        let prom = new Promise((resolve) => {
            resolver = resolve;
        })

            this.__HTTP_GET_STR(path)
                    .then((res) => {
                        resolver(JSON.parse(res))
                        window.$v3.doNothing('res of http get type---:', window.$v3.$typeof(res))
                    })
        

        // prom.__isMock = false;
        // let isLocalMode = window.$v3.$utils.isDevServer();
        // prom.mock = function (isMock = false) {

        //     if (isLocalMode) {
        //         prom.__isMock = true;
        //     }
        //     if (isMock === true) {
        //         prom.__isMock = true;
        //     }
        //     return prom;
        // }
        // let self = this;

        // prom.real = function (fn) {
        //     if (prom.__isMock) {
        //         return prom;
        //     }
        //     window.$v3.doNothing('fnnnnnnnnnnnnn-:', fn, window.$v3.$typeof(fn))

        //     if (window.$v3.$typeof(fn) == 'function') {
        //         fn(resolver);
        //     } else {
        //         throw "argu $1 of resolve must be one function"
        //     }

        //     return prom;
        // }
        // prom.done = (fn) => {
        //     prom.then((res) => {
        //         fn(res)

        //         return res;
        //     })
        //     return prom;
        // }


        // setTimeout(() => {
        //     if (prom.__isMock) {
        //         window.$v3.doNothing('this of json---:', self, (self.__HTTP_GET_STR))
        //         self.__HTTP_GET_STR(path)
        //             .then((res) => {
        //                 resolver(JSON.parse(res))
        //                 window.$v3.doNothing('res of http get type---:', window.$v3.$typeof(res))
        //             })
        //     } else {
        //         prom.real(() => void 0)
        //     }
        // })



        return prom;
    }
    else {
        throw path + ' must ends with .js or '+DOT_MFC_POSTFIX_STR+' or .json or .m.js or .mless'
    }
}

export const _REQUIRE = __REQUIRE;

let __REQUIRE_FUN_STR = __REQUIRE.toString()
let __HTTP_GET_STR = u.httpGet.toString()
let __INSERT_GLOBAL_STYLE = loadCss.toString()


let mfc3KeysArr = Object.keys(window.MFC).filter(s => (!('ref'.split(' ').includes(s))))
let _MFC_BUILD_IN_VAR_DEFINE_STR = `const {${mfc3KeysArr.join(',')}}=window.MFC;`

async function parseMFC(path) {
    path=path.replace('mfc-src/mfc-src','mfc-src')
    let _path_ = path.split('?')[0];
    let __COMPONENT_NAME = (path.split('?')[0].split('/').reverse()[0].split('.')[0]);
    window.$v3.doNothing('__COMPONENT_NAME----:', __COMPONENT_NAME)
    let pathOfParseMfc = path
    pathOfParseMfc=pathOfParseMfc.replace('mfc-src/mfc-src','mfc-src')
    // debugger


    let self = this;
    // console.log('pathhhhhhhh------:', path)
    let str = await u.httpGet(path, true);
    if (typeof (window.$v3?.bizConfig?.transformMfcFileContent) == 'function') {
        str = window.$v3?.bizConfig?.transformMfcFileContent(str, path.split('?')[0].split(DOT_MFC_POSTFIX_STR)[0]) || str
    }
    let div = document.createElement('div');
    div.innerHTML = str;
    // let tpl=div.querySelector('template')?.innerHTML;
    // window.$v3.doNothing('tpl---:',tpl,str)




    let tpl = ((str.split('<template>')[1] || '')
        .split('</template>').slice(0, -1).join('</template>') || '')
        // .split('</template>')

        //     [0]||'')
        || '<div></div>';//
    // tpl=tpl.replace(/'/gi,'"')
    window.$v3.doNothing('tpltpltpltpltpltpltpltpltpltpltpl--:', tpl)
    let oldWindowDefineComponent = window.defineComponent
    let scriptTag = div.querySelector('script')
    let windowProvideResolver = Promise.resolve(void 0);

    // window.$v3.doNothing("MFC-----:",scriptTag.getAttribute('MFC')===null)
    let isMFCMode=false;
    if (scriptTag && (scriptTag.getAttribute('MFC') !== null || scriptTag.getAttribute('mfc') !== null)) {
        isMFCMode=true;
        let baseP = (path) => path.split('/').slice(0, -1).join('/')
        let arrByQuestionMarkSplit = path.split('?');
        let rightStrOfQuestionMark = arrByQuestionMarkSplit.slice(1).join('?')
        let fileN = (path) => arrByQuestionMarkSplit[0].split('/').reverse()[0].split('.')[0]
        let jsxFilePath = baseP(path) + '/' + fileN(path) + '.m.js' + (rightStrOfQuestionMark ? ('?' + rightStrOfQuestionMark) : '')
        jsxFilePath += ('?_rand=' + Math.random())
        // alert(jsxFilePath)
        // jsxFilePath+=window.$v3.$utils.isDevServer()?('?_rand='+Math.random()):''
        // window.$v3.doNothing('path in mfc--:',path,baseP(path),fileN(path),jsxFilePath)
        // let __CURRENT_MODULES_DEPS_OLD=window?.defineComponent.__CURRENT_MODULES_DEPS
        // console.log('path in mfc parser--:',path)
        
        window.defineComponent = (obj) => {
            let isOnlyDefinedSetup = Object.keys(obj).length == 1 && ('setup' in obj)


            let depedComps = Array.from(window.defineComponent.__CURRENT_MODULES_DEPS_COMPONENTS);
            window.$v3.doNothing('depedComps---:', depedComps)
            if (!('components' in obj) && depedComps.length) {
                obj.components = depedComps
            }
            // debugger;

            // debugger;
            let isConfigInObj = '$config' in obj;
            // let symbolKey=Symbol();


            if ('$config' in obj && ((typeof (obj.$config) != 'function'))) {
                throw '$config must be one function in mfc mode[' + jsxFilePath + ']'
            } else {
                // obj[symbolKey]=obj.components;
                obj.$config = obj.$config || (function $config() {
                    // window.$v3.doNothing('this in config--:',this)
                    return {
                        components: this.components
                        // components:['../component-test'+DOT_MFC_POSTFIX_STR]
                    }
                    // let resp={}
                    // if(obj.components){
                    //     resp.components=obj.components;
                    // }
                    // return resp;
                })

            }
            if ('setup' in obj && ((typeof (obj.setup) != 'function'))) {
                throw 'setup must be one function in mfc mode[' + jsxFilePath + ']'
            } else {
                obj.setup = obj.setup || (() => ({}))
            }
            for (let i in obj) {
                if (i != '$config' && i != 'setup' && i != 'components' && !(typeof (i) == 'symbol')) {
                    throw i + ' is not allowed to use in mfc mode[' + jsxFilePath + ']'
                }
            }

            let configStr = obj.$config.toString()
            let setupStr = obj.setup.toString()
            window.defineComponent.__SETUP_FNS[path] = obj.setup;

            let configStrFirstLineContent = configStr.trim().split('\n')[0];
            let setupStrFirstLineContent = setupStr.trim().split('\n')[0]
            let isIncludeFunction = (str) => {
                return str.includes('function ') || str.includes('function(')
            }

            if (isConfigInObj && !configStrFirstLineContent.includes('=>')) {
                throw '$config must use arraw function in mfc mode[' + jsxFilePath + ']'
            }
            if (!setupStrFirstLineContent.includes('=>') && !isOnlyDefinedSetup) {
                throw 'setup must use arraw function in mfc mode[' + jsxFilePath + '] when exprt default one function which retruned an object'
            }

            configStr = ((configStrFirstLineContent.includes('=>')) ? '' : (isIncludeFunction(configStrFirstLineContent) ? '' : 'function ')) + configStr
            setupStr = ((setupStrFirstLineContent.trim().split('\n')[0].includes('=>')) ? '' : (isIncludeFunction(setupStrFirstLineContent) ? '' : 'function ')) + setupStr

            //  if(window.$v3.$utils.isDevServer()){

            //     if(window.defineComponent.__CURRENT_MODULES_DEPS){
            //         for(let i in window.defineComponent.__CURRENT_MODULES_DEPS){
            //             // configStr=`((window.$v3.doNothing('${i}---------------',${i})),${configStr})`
            //             // setupStr=`((window.$v3.doNothing('${i}---------------',${i})),${configStr})`
            //         }
            //     }

            //     window.configStr=configStr;
            //     window.setupStr=setupStr;
            //  }


            let str = `export default {
                $config:${configStr},
                setup:${setupStr},
                components:${JSON.stringify(obj.components)}

             }`;
            //  debugger;
            scriptTag = {
                innerHTML: str
            }

            window.str = str;

            return '__DEFINE_COMPONENT'
        }

        if (!window.defineComponent.__SETUP_FNS) {
            window.defineComponent.__SETUP_FNS = {}
        }

        let oldWindow$provider = window.$Provide;


        window.$Provide = async function (obj) {
            // alert('provide invoked')
            if (!typeof (obj) == 'object' || obj === null) {
                throw 'param of $Provide must be one obj'
            }
            let _resolve;
            windowProvideResolver = new Promise((resolve) => {
                _resolve = resolve;
            })
            let promiseArrRes = await Promise.all(Object.values(obj).map(s => (s instanceof Promise ? s : Promise.resolve(s))));
            _resolve();
            // window.abcde=promiseArrRes
            promiseArrRes.forEach((item, index) => {
                if (Object.keys(item).length == 1 && item.default) {
                    obj[Object.keys(obj)[index]] = item.default;
                }
            })


            // window.$v3.doNothing('promiseArrRes-',obj)


            if (!window.defineComponent.__CURRENT_MODULES_DEPS) {
                window.defineComponent.__CURRENT_MODULES_DEPS = {}
            }
            window.defineComponent.__CURRENT_MODULES_DEPS[pathOfParseMfc] = obj;
            setTimeout(() => {
                delete window.$Provide
                if (oldWindow$provider) {
                    window.$Provide = oldWindow$provider
                }
            })
        }

        window.__COMPONENT_NAME = __COMPONENT_NAME;

        let oldWindowRequire = window.require;
        if (!window.defineComponent.__CURRENT_MODULES_DEPS_COMPONENTS) {
            window.defineComponent.__CURRENT_MODULES_DEPS_COMPONENTS = []
        }
        window.require = function(s) {
           
            if (!s.toLowerCase().endsWith(DOT_MFC_POSTFIX_STR)) {
                throw 'can not require a file which not ends with '+DOT_MFC_POSTFIX_STR
            }
            return window.defineComponent.__CURRENT_MODULES_DEPS_COMPONENTS.push(s);
        }
        let res = await window.__IMPORT(jsxFilePath).catch((e) => {
            throw e;
            //    console.log('err--:',e)
        });

        // alert(path+'-----2')
        // setTimeout(()=>{
        delete window.__COMPONENT_NAME

        if (oldWindowRequire) {
            window.require = oldWindowRequire
        } else {
            delete window.require;
        }
        // })



        await windowProvideResolver;
        // debugger



        let obj;
        if (typeof (res.default) == 'function') {
            if (res.default.name == 'setup') {
                obj = {
                    setup: res.default
                }
            } else {
                obj = res.default()
            }

            // if(obj!=='__DEFINE_COMPONENT'){
            //     window.defineComponent(obj)
            // }
        }
        else if (res.default !== '__DEFINE_COMPONENT') {
            obj = res.default;

        }

        window.defineComponent(obj)

    }
    let jsStr = scriptTag?.innerHTML?.trim() || 'export default {}'
    // window.$v3.doNothing("jsStr==:",jsStr)



    // doConsoleLog('jsStr---:',jsStr,path)
    // window.$v3.doNothing('js str---:',jsStr)
    // alert(jsStr.startsWith('export '))
    if (jsStr.startsWith('export ')) {
        let firstBracesSplitedArr = jsStr.split('{'),
            $1 = firstBracesSplitedArr[0].trim(),
            $2 = firstBracesSplitedArr.slice(1).join('{').trim()
        // alert($1)
        let isEndsWithDefineComponent = $1.endsWith(' default defineComponent(')
        // alert($1.endsWith(' default') ||isEndsWithDefineComponent)
        if ($1.endsWith(' default') || isEndsWithDefineComponent) {

            let varDefine = _MFC_BUILD_IN_VAR_DEFINE_STR;
            // let varDefine="const {reactive,watch,computed,onBeforeUnmount,onMounted,defineEmits,onUpdated}=window.MFC;"
            varDefine += 'const ref=(p,cb=()=>{})=>{let refResult=window.MFC.ref(p);cb(refResult);return refResult;};'
            varDefine += 'const $i18n=window.$v3.$mixins.i18nMixin;'
            // varDefine+='const defineComponent=(s)=>s;'
            varDefine += 'const windowResize$=window.$v3.$mixins.windowResizeMixin;'
            varDefine += 'const clickMixin$=window.$v3.$mixins.clickMixin;'
            varDefine += 'const $store=(obj,fn)=>{let res=window.$v3.$mixins.storeMixin(obj); if(typeof(fn)==="function"){fn(res)} return res;};'
            // varDefine+='const $logger=window.$v3.$mixins.loggerMixin;'
            varDefine += 'const $module=window.$v3.$mixins.moduleMixin;'

            varDefine += `const useJsModule$=(key)=>{
                if(typeof($)=='function'){
                    $();
                }
                return $.type.$config.modules[key]||null;
                // window.$v3.doNothing('$$$$$$$$--:',$);
            };`

            varDefine += 'const $v2=window.$v3.$mixins.renderV2ComponentMixin;'
            varDefine += 'const html$=window.$v3.html;'
            varDefine += 'const onMounted$=(fn)=>{ onMounted(()=>{  fn($setupRes)   })  };'
            varDefine += 'const onActivated$=(fn)=>{ onActivated(()=>{  fn($setupRes)   })  };'
            varDefine += 'const onBeforeMount$=(fn)=>{ onBeforeMount(()=>{  fn($setupRes)   })  };'

            varDefine += `let _setupFn$=(window?.defineComponent?.__SETUP_FNS||{})['${_path_}']||null;`
            // varDefine+='const style$=(fn)=>{ onMounted(()=>{  fn($setupRes)   })  };'
            varDefine += 'var $setupRes={};'
            // varDefine+='const echarts=window.$v3.echarts;'
            varDefine += 'const service$={};'
            varDefine += 'let $emit;$emit=()=>{throw "If you want to use $emit,please firstly invoke $ method in the beginning of the setup method body"};\n\n\n\n'

            // let tempStr=''
            // varDefine+=(function(){
            //     let str='';
            //     let globalMethods=self?.__globalMethods
            //     if(globalMethods){
            //         for(let i in globalMethods){
            //             if (!"require log alert".split(" ").includes(i)) {
            //                 str+=`let ${i};${i}=()=>{
            //                     throw "If you want to use ${i},please firstly invoke $ method in the beginning of the setup method body"};\n\n`
            //                     tempStr+=`${i}=$.type.globalMethods.${i};`
            //                     // tempStr+=`${i}=$.type.globalMethods.${i};`
            //             }


            //         }
            //     }


            //     return str;
            // })();

            // varDefine+='let $v2Emit;$v2Emit=()=>{throw "If you want to use $v2Emit,please firstly invoke $ method in the beginning of the setup method body"};'
            // ${tempStr}
            varDefine += `\n\n\n\nlet $=function(){$=$.getCurrentInstance();
                
                $emit=($||{emit(){ console['log']('$--:',$);throw 'called a not existed $' }}).emit;
                
                //这里原先有一个tempStr，去掉了，具体参考上文

                if(window.$v3.$utils.isDevServer() && $?.type){
                    window[$.type.name]=$;
                    window.$$=$;
                    // window.$v3.doNothing("$ in debug---:",$)
                }
                
                return $;};$.getCurrentInstance=window.MFC.getCurrentInstance;let $$;`


            // varDefine+='const print$=(obj)=>{let result=window.$v3.$mixins.printMixin(obj,true);for(let i in result){$setupRes[i]=result[i]}     return {...___additionalSetupRes,...$setupRes};};'
            varDefine += 'const ___additionalSetupRes={};'
            varDefine += 'const result$=(obj)=>{let result=obj;for(let i in result){$setupRes[i]=result[i]}     return {...___additionalSetupRes,...$setupRes,result$};};'
            varDefine += 'result$.add=function(k,v,fn=()=>{}){  ___additionalSetupRes[k]=v;    if(typeof(fn)=="function"){  (typeof($)=="function"?$():$);$$=$;let config$={data$:___additionalSetupRes,staticData:$setupRes};result$.config$=config$;   fn(v,config$,$)         }  ;return result$;    };'

            // varDefine+=`let HTTP_GET=new Function(${` \`return ${__HTTP_GET_STR} \` `})().bind(null);`//
            varDefine += `;var __COMPONENT_NAME='${__COMPONENT_NAME}';`;
            // window.$v3.doNothing('window?.defineComponent?.__CURRENT_MODULES_DEPS---:',window?.defineComponent?.__CURRENT_MODULES_DEPS)
            // alert(window?.defineComponent?.__CURRENT_MODULES_DEPS)
            let _moduleDeps = (window?.defineComponent?.__CURRENT_MODULES_DEPS || {})[pathOfParseMfc] || { ___DO_NOT_USE_THIS_VAR: null };
            // debugger;
            varDefine += `\n;var {${Object.keys(_moduleDeps).join(',')}}=(window?.defineComponent?.__CURRENT_MODULES_DEPS||{})['${pathOfParseMfc}']||{___DO_NOT_USE_THIS_VAR:null};`;
            // varDefine+=`\n;var {${Object.keys(_moduleDeps).join(',')}}=(window?.defineComponent?.__CURRENT_MODULES_DEPS||{})['${pathOfParseMfc}']||{___DO_NOT_USE_THIS_VAR:null};`;
            varDefine += `let ___wrapperRes$=(obj)=>{
                // let _setupFn$=(window?.defineComponent?.__SETUP_FNS||{})['${_path_}']||null;
                // window.$v3.doNothing("_setupFn$ in wraper res--:",_setupFn$,obj)
                // if(typeof(obj.setup)=='function' && _setupFn$){
                //     obj.setup=_setupFn$
                // }
                // if(typeof(obj.setup)=='function'){
                //     let setupStr=obj.setup.toString();
                //     obj.setup=new Function('return function '+setupStr)
                //     // let oldSetup=obj.setup;
                //     // obj.setup=function(p1,p2,p3,p4,p5){
                //     //     // $();
                //     //     oldSetup(p1,p2,p3,p4,p5)
                //     //     // oldSetup.apply(window,arguments)
                //     // }
                // }
                return obj;
            };`
            $1 = varDefine + `let Mfc=window.MFC;let require=new Function(${` \`return ${__REQUIRE_FUN_STR} \` `})()
                .bind({thisPath:'${path}'
                ,__INSERT_GLOBAL_STYLE:${__INSERT_GLOBAL_STYLE}
                ,__HTTP_GET_STR:${__HTTP_GET_STR}
                ,DOT_MFC_POSTFIX_STR:"${DOT_MFC_POSTFIX_STR}"
            
            });return ___wrapperRes$(`+ (isEndsWithDefineComponent ? '({' : '{')//
            // window.$v3.doNothing("$2---:",$2)
            // $1=`let require=window.__REQUIRE.bind('${path}');return {`//
            let str = $1 + $2 + ')';
            // window.$v3.doNothing('evaled str---:',str)


            let obj = new Function(str)();
            // window.$v3.doNothing("obj---:",obj)

            if (typeof (obj?.$config) == 'function') {
                obj.$config = await obj.$config()
            }


            if (window.$v3.$typeof(obj?.$config?.modules) == 'function') {
                let o = obj?.$config || {}
                if (o.modules) {
                    o.modules = obj?.$config?.modules()
                }

            }

            let jsModuleMap = obj?.$config?.modules || {}
            let keys = Object.keys(jsModuleMap)
            // window.$v3.doNothing('obj and js module ar--;',obj,jsModuleMap)
            if (keys.length) {
                let arr = await Promise.all(Object.values(jsModuleMap))
                // let arr=await Promise.all(jsModuleMap.map((item)=>Object.values(item)[0].__PROM))
                // window.$v3.doNothing('arrrrrrrrrrrr----------:',arr)//
                arr.forEach((row, index) => {
                    (obj?.$config || {})['modules'][keys[index]] = row;
                    // (obj?.$config||{})['$'+(Object.keys(jsModuleMap[index])[0])]=row;
                })
                doConsoleLog("obj---:", obj)
            }

            // window.$v3.doNothing('tpl--:',tpl)

            // let theFinalComps=


            // if(path.endsWith('mfc-app'+DOT_MFC_POSTFIX_STR)){
            //     let c=obj.components;
            //     debugger;
            // }
            let res = {
                _isMFCMode:isMFCMode,
                __path: path,
                name: path.split('/').reverse()[0].split(DOT_MFC_POSTFIX_STR)[0],
                template: tpl,
                ...obj,
                props: {
                    // store:Object,
                    vm: Object,//mfc2 only
                    state: Object,
                    t: [Function, Object],
                    v2Comps: Array,
                    src:String,
                    ...obj.props
                },
                components: {
                    ...obj.components,
                    ...(await (async function () {
                        if (obj?.$config && typeof (obj?.$config?.components) == 'function') {
                            obj.$config.components = obj.$config.components()
                        }
                        let cArr = obj?.$config?.components || []
                        cArr.forEach((item, index) => {
                            if (typeof (item) == 'string') {






                                //                     $1=varDefine+`let require=new Function(${` \`return ${__REQUIRE_FUN_STR} \` `})()
                                //     .bind({thisPath:'${path}'
                                //     ,__INSERT_GLOBAL_STYLE:${__INSERT_GLOBAL_STYLE}
                                //     ,__HTTP_GET_STR:${__HTTP_GET_STR}

                                // });`//


                                let bindedObj = {
                                    thisPath: path
                                    , __INSERT_GLOBAL_STYLE: __INSERT_GLOBAL_STYLE
                                    , __HTTP_GET_STR: __HTTP_GET_STR
                                    , DOT_MFC_POSTFIX_STR: DOT_MFC_POSTFIX_STR
                                }
                                window.$v3.doNothing('bindedObj---:', bindedObj)
                                let req = new Function(` return ${__REQUIRE_FUN_STR} `)()
                                window.$v3.doNothing('reqqqqqqqq----:', req)
                                req = req.bind(bindedObj)

                                cArr[index] = req(item)
                            }
                        })
                        if (typeof (cArr) == 'function') {
                            cArr = cArr()
                        }
                        doConsoleLog('cArr---:', cArr);

                        if (!cArr.length) {
                            return {}
                        } else {
                            let map = {}

                            // if(path.endsWith('mfc-app'+DOT_MFC_POSTFIX_STR)){
                            //     let c=cArr;
                            //     debugger;
                            // }

                            let arr = await window.$v3.$utils.sequenceExecPromiseArr(cArr.map((path) => {
                                return () => {
                                    return parseMFC.call(self, path)
                                }
                            }))
                            // let arr=await Promise.all(cArr.map((path)=>parseMFC.call(self,path)))
                            // console.log('arrrrrrrrrr---:',arr)
                            arr.forEach((item) => {
                                // map[item.__path.split('/').reverse()[0]]=item
                                map[item.__path.split('/').reverse()[0].split(DOT_MFC_POSTFIX_STR)[0]] = item
                            })
                            doConsoleLog('map---:', map);
                            return map;
                        }

                    })()),
                }
            }
            // if(window.$v3.$utils.isDevServer()){
            res.created = function () {
                // alert(res.__path)

                window.MFC.onBeforeUnmount(() => {
                    let k = res.__path.toLowerCase().split('/').reverse()[0].split(DOT_MFC_POSTFIX_STR)[0];

                    try {
                        delete window.$vmInstance[k]
                        delete window[k]
                        // window.$v3.doNothing('clear vm instance key and value')

                    } catch (e) {

                    }
                })

                if (!window.$vmInstance) {
                    window.$vmInstance = {}
                }
                let instanceKey = res.__path.toLowerCase().split('/').reverse()[0].split(DOT_MFC_POSTFIX_STR)[0]
                // window.$vmInstance[instanceKey]=[window.$vmInstance[instanceKey]||[],this].flat()
                // if(window.$vmInstance[instanceKey].length==1){
                //     window.$vmInstance[instanceKey]=window.$vmInstance[instanceKey][0]
                // }
                window.$vmInstance[instanceKey] = this;
                window.$vmInstance[instanceKey]._d = () => {
                    return Object.fromEntries(Object.entries(window.$vmInstance[instanceKey]._.setupState))
                }

                window.$v3.doNothing('this in res created---:', this, res)
            }

            // }

            // window.$v3.doNothing('res----------',res)
            if (this?.__globalMethods) {
                res.globalMethods = this?.__globalMethods
            }

            // if(window.$v3.$utils.isDevServer()){
            // if(!window.$v3.$utils.isDevServer()){
            delete window.defineComponent;
            
            // }

            if (oldWindowDefineComponent) {
                window.defineComponent = oldWindowDefineComponent
            }
            return res;
        } else {
            throw 'not starts with export default'
        }

    } else {
        if (jsStr.startsWith('import ')) {
            throw "can not starts with import";
        } else {
            throw 'not starts with export default '
        }

    }

    // doConsoleLog('str---:',str)
}


export default parseMFC;